import java.io.*
import java.lang.Exception
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.CopyOnWriteArrayList
var list =CopyOnWriteArrayList<Channel>()
fun main(args: Array<String>) {
    println("Server启动....")
    val server:ServerSocket= ServerSocket(8889)
    var isServerRunning=true
    while(isServerRunning){
        //阻塞等待客户端连接
        val client:Socket=server.accept()
        val channel=Channel(client)
        //通过遍历容器获取其他通道内的消息然后转发给其他用户
        list?.add(channel)
        println("一个客户端建立了连接")
        Thread(Channel(client)).start()
    }
    server.close()
}
//一个Channel代表一个连接通道
class Channel(private val client:Socket):Runnable{
    private val dis:DataInputStream = DataInputStream(client.getInputStream())
    private val dos:DataOutputStream= DataOutputStream(client.getOutputStream())
    var isRunning=true
    override fun run() {
        while (isRunning){
            try {
                val msg=receive()
                list.forEach {
                    if(it!=this){
                        it.send(msg)
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                release()
            }
        }
    }
    private fun receive():String{
        var msg:String=""
        try {
           msg= dis.readUTF()
        }catch (e:Exception){
            println("server error code:1")
            release()
        }
        return msg
    }
    private fun send(msg:String){
        try {
            dos.writeUTF(msg)
        }catch (e:Exception){
            println("server error code:2")
            release()
        }
    }
    private fun release(){
        isRunning=false
        ChatUtils.release(client,dis,dos)
    }
}